﻿using Application.Commons.Data;
using AutoMapper;
using Domain.Entities.Customers;
using FrameworkCore.Models;
using MediatR;
using NM.Module.Cust.API.DTOs;
using NM.Module.Cust.API.Specifications;
using System.Text.Json.Serialization;
using System.Linq.Dynamic.Core;
using FrameworkCore.Extensions;

namespace NM.Module.Cust.API.Queries.PaginationQuery;


/// <summary>
/// 用户分页查询
///</summary>
public class CustomersWithPaginationQuery : CustomerAdvancedFilter, IRequest<PaginatedData<CustomerOutput>>
{
    [JsonIgnore]
    public CustomerAdvancedPaginationSpec Specification => new CustomerAdvancedPaginationSpec(this);
}

/// <summary>
/// 处理程序
/// </summary>
public class CustomersWithPaginationQueryHandler : IRequestHandler<CustomersWithPaginationQuery, PaginatedData<CustomerOutput>>
{
    private readonly IMapper _mapper;
    private readonly ApplicationDbContext _context;
    public CustomersWithPaginationQueryHandler(
    ApplicationDbContext context,
    IMapper mapper)
    {
        _context = context;
        _mapper = mapper;
    }

    /// <summary>
    /// 业务逻辑
    /// </summary>
    /// <param name="request">请求参数</param>
    /// <param name="cancellationToken">取消标记</param>
    /// <returns>返回用户分页数据</returns>
    public async Task<PaginatedData<CustomerOutput>> Handle(CustomersWithPaginationQuery request, CancellationToken cancellationToken)
    {
        return await _context.Customers.OrderBy($"{request.OrderBy} {request.SortDirection}")
            .ProjectToPaginatedDataAsync<Customer, CustomerOutput>(
            request.Specification,
            request.PageNumber,
            request.PageSize,
            _mapper.ConfigurationProvider,
            cancellationToken);
    }
}